define(["text!./player_live_widget.html",
    "../../service",
    "../../utils/i18n",
    // "../../assets/vendor/oniui/dialog/avalon.dialog"
    // "../../assets/vendor/onlineShowPlayer"

], function(sourceHTML, api, i18n) {

    var widget = avalon.ui.playerlivewidget = function(element, data, vmodels) {
        var vmodel = avalon.define(data.playerlivewidgetId, function(vm) {


            vm.error = {
                errorCode: 2,
                message: "正在等待信号..."
            }
            vm.isPlay = false;
            vm.password = ""
            vm.passwordState = ""
            vm.errObj = ""
            vm.$player = avalon.mix({}, data.playerlivewidgetOptions);
            vm.$init = function() {

                if (vm.$player.stateName != "lives.item" && vm.$player.stateName != "onlines.item") {
                    vm.updatePlayerState()
                } else {
                    vm.$watch("onlineStateChange", function(player) {
                        if (!vm.$player.VideoResourcePath) vm.$player.VideoResourcePath = {};
                        vm.$player = _.merge(vm.$player, player);
                            vm.onlinePlayerState();
                        
                    })
                }
                element.innerHTML = sourceHTML;
                avalon.scan(element, [vmodel].concat(vmodels))
                
            }
            vm.errorMessage = {
                "001": "您找的记录不存在",
                "4": "未有直播信号",
                "3": "信号中断，正在重连..."
            }
            vm.$password = {
                title: "输入观看密码：",
                modal:true
            }
            vm.updatePlayerState = function() {

                var state = vm.$player.VideoResourcePath;

                if (state && state.errorCode) {
                    vm.error = {
                        errorCode: parseInt(state.errorCode),
                        message: vm.errorMessage[state.errorCode] || state.message
                    }

                } else if (state && vm.$player.smil) {

                    vm.error.errorCode = 0;

                    setTimeout(function() {
                        var uri = vm.$player.VideoResourcePath.data;
                        loadPlayer = false;
                        var tmp =  createPlayer(uri, { seekTime: vm.$player.seekTime, isPlay: vm.isPlay },vm.$player.smil,vm.$player.timeinfo,vm.$player.Video,vm.$player.videoSW)
                        if(!_.isEmpty(tmp)){
                            vm.error = tmp
                        }
                        vm.isPlay = true;

                    }, 100);

                } else {
                    vm.error = {
                        errorCode: parseInt(state.errorCode) || 2,
                        message: state.message || ""
                    }

                }
            }
            vm.onlinePlayerState = function() {
                var state = vm.$player.VideoResourcePath;
                var _error = vm.$player.error;

                if(_error&&_error.errorCode == 5){
                    vm.error = {};
                    vm.error = _error;

                    window.jw = null;
                    window.hls = null;
                     window.vlc = null;
                    return;
                }


                if (!state) {
                    vm.error = {
                        errorCode: 4,
                        message: vm.errorMessage["4"]
                    }
                    window.jw = null;
                    window.hls = null;
                     window.vlc = null;
                    return; 
                }
                if (_.isEmpty(state.data)) {
                    vm.error = {
                        errorCode: parseInt(state.errorCode) || 4,
                        message: state.message || "无节目信息"
                    }

                } else if ((state.data.RecordEquipmentCode == 2 || state.data.RecordEquipmentCode == 3)) {


                    if ((window.jw || window.vlc || window.hls)) {

                        if (state.data.AgentServerCode == 3||state.data.AgentServerCode == 1) {
                            if (vm.isPlay) {
                                return;
                            }
                        } else {
                            vm.error = {
                                errorCode: 3,
                                message: vm.errorMessage["3"]
                            }
                            window.jw = null;
                            window.hls = null;
                            window.rtsp = null;

                            vm.isPlay = false;
                            return;
                        }
                    }
                    
                    var uri = state.data.Uri;
                    if (!_.isEmpty(uri)) {

                        // vm.error.errorCode = 0;

                        setTimeout(function() {

                            if (state.data.viewPassword && state.data.viewPassword != "") {
                                
                                vm.error.errorCode = 999;
                                vm.submitPassword = function(){
                                    if(vm.password == state.data.viewPassword){
                                         loadPlayer = false;

                                        var tmp = createPlayer(uri, { isPlay: vm.isPlay })
                                        if(!_.isEmpty(tmp)){
                                            vm.error = tmp
                                        }
                                        vm.isPlay = true;
                                        
                                    }else{
                                        vm.passwordState = "密码错误，请重试输入！"
                                    }
                                }

                            } else {
                                loadPlayer = false;
                                var tmp = createPlayer(uri, { isPlay: vm.isPlay })
                                if(!_.isEmpty(tmp)){
                                    vm.error = tmp
                                }

                                vm.isPlay = true;
                            }
                        }, 100);

                    } else {
                        vm.error = {
                            errorCode: parseInt(state.data.RecordEquipmentCode),
                            message: "等待直播信号..."
                        }

                    }
                } else if (state.data.RecordEquipmentCode == 0 || state.data.RecordEquipmentCode == 7 || state.data.RecordEquipmentCode == -1) {
                    vm.error = {
                        errorCode: parseInt(state.data.RecordEquipmentCode),
                        message: "未有直播信号"
                    }

                    window.jw = null;
                    window.vlc = null;
                    window.hls = null;
                } else {
                    var errorCode = state.data ? parseInt(state.data.RecordEquipmentCode) : 1
                    vm.error = {
                        errorCode: errorCode,
                        message: "未有直播节目"
                    }
                    window.jw = null;
                    window.vlc = null;
                    window.hls = null;
                }

            }

            vm.submitPassword = function(){}
            vm.keySubmit = function(e){
                vm.passwordState = ""
                e = document.all ? window.event : e;
                if(e.keyCode==13)
                    vm.submitPassword()
            }
            vm.$remove = function() {
                window.jw = null;
                window.vlc = null;
                window.hls = null;
                vm.$unwatch("subChange")
                vm.$unwatch("onlineStateChange")
                element.innerHtml = element.textContent = "";
            }

            vm.$watch("videopathUpdate", function(player) {

                if (!vm.$player.VideoResourcePath) vm.$player.VideoResourcePath = {};
                vm.$player.VideoResourcePath = _.merge(vm.$player.VideoResourcePath, player.VideoResourcePath);
                vm.onlinePlayerState()    
                
            })
            vm.$watch("setting", function(setting) {
                vm.$settting = avalon.define(
                    avalon.mix(vm.$setting, setting))
            })
            vm.$watch("subChange", function(_sub) {

                window.jw = null;
                window.vlc = null;
                window.hls = null;

                vm.$player.VideoResourcePath = {}
                vm.error = {
                    errorCode : 10,
                    message : "正在等待信号..."
                }
            })
 
        }) 
        return vmodel;
    }

    return avalon;
 


    function MobileClient() {
        //以下是判断是否在移动客户端
        var sUserAgent = navigator.userAgent.toLowerCase();
        var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
        var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
        var bIsAndroid = sUserAgent.match(/android/i) == "android";
        if (bIsIpad || bIsIphoneOs || bIsAndroid) {
            return true;
        }
        return false;
    }

    var loadPlayer = false;
    var playerType;
    var $setting = {};
    var isPlay = true;
    var PlayerIsPlaying = function PlayerIsPlaying() {
        //根据当前正在用的播放器返回是否播放中
        if (playerType == "rtsp") {
            //这里是判断VLC播放器是否为播放中
            var vlcPlayer = document.getElementById("OnlinePlayer");
            if (vlcPlayer != null) {
                if (vlcPlayer.state != 3) //3是播放 4是暂停 0未播放
                {
                    loadPlayer = false;
                    return false;
                }
                return true;
            }
        }
        //这里是判断jwplayer是否播放中
        if (playerType == "rtmp") {
            //这里是判断VLC播放器是否为播放中
            //var vlcPlayer = document.getElementById("OnlinePlayer") //$("#OnlinePlayerContainer").fuvlc("OnlinePlayer")[0];
            var player = jwplayer("OnlinePlayer");
            //alert(player);
            //alert(player.getState());
            if (player != null && typeof(player.getState) != "undefined" && player.getState() == "playing") {

                return true;
            } else {
                loadPlayer = false;
                return false;
            }
        }

        //这里是判断H5<video>标签是否播放中
        if (playerType == "http") {
            var html5Player = document.getElementById("OnlinePlayer");
            if (html5Player != null) {
                if (html5Player.played == null) {
                    loadPlayer = false;
                    return false;
                }
                return true;
            }
        }

        //默认返回false
        return false;
    }
    var PlayerHash = "";

    function LoadPlayer(player) {
        playerType = player;

        if (loadPlayer) {
            //已加载的话
            return;
        }
        var w = '100%';
        var h = '100%';
        //去掉加载画面
        // $('#OnlinePlayerContainer').html("");
        if (player == "rtsp") {
            var vlc = "<object type='application/x-fb-vlc' id='OnlinePlayer' name='OnlinePlayer' height='670' width='1192' events='true'><param name='wmode' value='opaque'><param name='windowless' value='true'><param name='mrl' value=''><param name='autoplay' value='true'><param name='loop' value='false'><param name='fullscreen' value='true'><param name='showdisplay' value='true'><param name='bgcolor' value='#222222'><param name='toolbar' value='true' /><param name='windowless' value='false'></object>"
            $('#OnlinePlayerContainer').html(vlc);
        } else if (player == "rtmp") {
            PlayerHash = new Date().getTime()
            var jwplayer = "<div type='application/x-shockwave-flash' id='OnlinePlayer" + PlayerHash + "' name='OnlinePlayer'>这里为多媒体播放器，如果看到当前内容，请确认浏览器开启了脚本支持和Flash插件。</div>";
            $('#OnlinePlayerContainer').html(jwplayer);

        } else if (player == "http") {
            var html5 = "<video id='OnlinePlayer' src='' width='1192' height='670'  autoplay='autoplay' controls='controls'></video>";
            $('#OnlinePlayerContainer').html(html5);
        }

        loadPlayer = true;
    }
 

    function createPlayer(Uri, options,smil,timeinfo,video,videoSW) {
        var rtmpUri = null;
        var rtmpUri_high = null;
        var rtspUri = null;
        var rtspUri_high = null;
        var hlsUri = null;
        //声明http播放地址
        if (Uri != null) {
            rtmpUri = Uri.RTMP;

            rtspUri = Uri.RTSP;
            //声明http播放地址
            hlsUri = Uri.HLS;

        } else {
            return;
        }

        console.log(video)
        var mobileClient = MobileClient();

        var gotoMobilePlayer = function(uri) {
            if (confirm("是否跳转到手机播器播放,如果没有自动跳转，请安装VLC播放器！")) {
                window.location.href = uri;
                return true;
            }
        }

        //var mobileClient = true;

        if (mobileClient == true && hlsUri != null && hlsUri.length > 0) {
            //当前是移动端，且有http播放地址，那么进行HTML5的Video播放
            LoadPlayer("http");
            var html5Player = document.getElementById("OnlinePlayer");
            //var source = document.getElementById("mp4_src");
            //source.src = httpUri;
            html5Player.src = hlsUri;
            window.hls = true;
            return {
                    errorCode: 0,
                    message: "等待直播中..."
                }
            //html5Player.load();
        } else if (mobileClient == true) {

            //当前为移动端，但没有hls播放地址的时候，提示弹出进行播放

            if (rtmpUri != null && rtmpUri.length > 0) {
                gotoMobilePlayer(rtmpUri);
            } else if (rtspUri != null && rtspUri.length > 0) {

                gotoMobilePlayer(rtspUri);
            }
            return {
                    errorCode: 0,
                    message: "等待直播中..."
                }
        } else {
            //说明不是移动端，那根据播放地址调用不同播放器
            //注，第一次拿到播放地址的时候，要根据播放地址去加载不同的播放器，和做界面的不同调整，比如说二代要显示出下面那些下载插件地址
            if (rtmpUri != null||smil) {
                if(rtmpUri){
                    rtmpUri = rtmpUri.replace("upload//", "upload/mp4:")
                }
                LoadPlayer("rtmp");


                var w = $(".player-wrapper").width();
                var h = $(".player-wrapper").height();

                var url
                    if(rtmpUri){
                       url = decodeURIComponent(rtmpUri);
                    }
                var zimu;    

                if(video&&video.captionsFileUri){
                    zimu = video.captionsFileUri;
                }


                window.jwConfig = {
                    tracks:[
                        {
                            file:zimu,
                            kind:'captions',
                            label:'Chinese',
                            "default": true
                        }
                    ],
                    primary: "flash",
                    flashplayer: "assets/tools/jwplayer.flash.swf",
                    skin: {
                        name: "glow",
                        url: "assets/skins/glow.css"
                    },
                    file: smil||url,
                    autostart: true,
                    screencolor: '000000',
                    wmode: 'transparent',
                    height: h,
                    width: w,
                    plugins: {
                    }
                }

                if (avalon.vmodels.header.$setting.vodMessage) {

                    window.jwConfig.plugins.brocasthelper = {
                        position: "top",
                        text: avalon.vmodels.header.$setting.vodMessage,
                        scrollspeed: 5,
                        fontSize: 30,
                        textcolor: "#fff",
                        backgroundcolor: "#000000"
                    }
                }
                if(timeinfo){
                    window.jwConfig.plugins.cuehelper = {
                        dockname:'知识点',
                        title:"课程名称:"+video.title,
                        introduction:video.remark,
                        repeatable:false,
                        oncomplete:false,
                        list_item_heght:40,
                        list_width:380,
                        file:timeinfo
                    }
                }
                if(videoSW){
                    window.jwConfig.plugins.cueswhelper = {
                        dockname:'教学环节',
                        title:"课程名称:"+video.title,
                        introduction:video.remark,
                        repeatable:false,
                        oncomplete:false,
                        list_item_heght:40,
                        list_width:380,
                        file:videoSW
                    }
                }

                jwplayer("OnlinePlayer" + PlayerHash).setup(jwConfig);
    
                if (options.seekTime){
                    // if http
                    // jwplayer("OnlinePlayer" + PlayerHash).onReady(function() {
                    //     setTimeout(function() { jwplayer("OnlinePlayer" + PlayerHash).seek(options.seekTime) }, 500)
                    // })
                    // if rtmp
                    jwplayer("OnlinePlayer" + PlayerHash).on("firstFrame",function(){
                        jwplayer("OnlinePlayer" + PlayerHash).seek(options.seekTime)
                    })
                }
                jwplayer("OnlinePlayer" + PlayerHash).onError(function(e){
                    // TODO...
                    // vm.errObj = e;
                    var errMes='';
                    if(e.message=="Error loading stream: Manifest not found or invalid"){
                        errMes = "加载视频流出错"
                    }
                    if(e.message=="Error loading stream: ID not found on server"){
                        errMes = "视频流不存在"
                    }
                    if(e.message=="Error loading stream: Could not connect to server"){
                        errMes = "服务器连接失败"
                    }
                    if(e.message=="Flash plugin failed to load"){
                        errMes = "播放器加载出现问题，请尝试刷新页面"
                    }
                    if(errMes==''){
                        errMes = e.message
                    }
                    $('#OnlinePlayerContainer').append('<div class="errCover"><div class="centerbox"><h3>播放失败</h3><h4>错误提示:'+errMes+'</h4></div></div>');

                    console.log(e)
                })
                window.jw = jwplayer("OnlinePlayer" + PlayerHash);
                window.player = null;
                return {
                    errorCode: 0,
                    message: "等待直播中..."
                }

            } else if (rtspUri != null) {

                LoadPlayer("rtsp");
                var vlcPlayer = document.getElementById("OnlinePlayer");
                //alert(vlcPlayer.playlist.playItem) ;
                if (vlcPlayer != null && typeof(vlcPlayer) != "undefined" && vlcPlayer.playlist && typeof(vlcPlayer.playlist.play) != "undefined") {
                    if (vlcPlayer.playlist.isPlaying) {
                        //vlcPlayer.stop();
                    }
                    //vlcPlayer.audio.volume = 200;
                    vlcPlayer.playlist.clear();
                    var options = new Array(':network-caching=5000');
                    options.push(":rtsp-tcp");
                    //if (playUri.indexOf("?model=rtsp-tcp") != -1
                    //    || playUri.indexOf("&model=rtsp-tcp") != -1) {
                    //    options.push(":rtsp-tcp");
                    //    //
                    //}
                    // flash(options);
                    //flash(playUri);

                    vlcPlayer.playlist.addWithOptions(rtspUri, options);
                    // 如果喜欢断线刷...
                    vlcPlayer.playlist.playItem(0); // 直接播放， 不用看是不是第一次播放。
                    if (typeof(LivePlay_FirstLoad) == "undefined") {
                        LivePlay_FirstLoad = false;
                    } else {
                        if (LivePlay_FirstLoad) {
                            vlcPlayer.playlist.playItem(0);
                            window.location.hash = "OnlinePlayerContainer";
                            LivePlay_FirstLoad = false;
                        }

                    }

                    playedTime = new Date();

                } else {
                        return {
                            errorCode: 5,
                            message: "请安装 VLC 播放器"
                        }
                }
                window.vlc = vlcPlayer
                return {
                    errorCode: 0,
                    message: "等待直播中..."
                }

            } else if(hlsUri != null){
                 LoadPlayer("rtmp");
                var w = $(".player-wrapper").width();
                var h = $(".player-wrapper").height();

                var url
                    if(hlsUri){
                       url = decodeURIComponent(hlsUri);
                    }
                var zimu;    

                if(video&&video.captionsFileUri){
                    zimu = video.captionsFileUri;
                }


                window.jwConfig = {
                    tracks:[
                        {
                            file:zimu,
                            kind:'captions',
                            label:'Chinese',
                            "default": true
                        }
                    ],
                    primary: "flash",
                    flashplayer: "assets/tools/jwplayer.flash.swf",
                    skin: {
                        name: "glow",
                        url: "assets/skins/glow.css"
                    },
                    file: smil||url,
                    autostart: true,
                    screencolor: '000000',
                    wmode: 'transparent',
                    height: h,
                    width: w,
                    plugins: {
                    }
                }

                if (avalon.vmodels.header.$setting.vodMessage) {

                    window.jwConfig.plugins.brocasthelper = {
                        position: "top",
                        text: avalon.vmodels.header.$setting.vodMessage,
                        scrollspeed: 5,
                        fontSize: 30,
                        textcolor: "#fff",
                        backgroundcolor: "#000000"
                    }
                }
                if(timeinfo){
                    window.jwConfig.plugins.cuehelper = {
                        dockname:'知识点',
                        title:"课程名称:"+video.title,
                        introduction:video.remark,
                        repeatable:false,
                        oncomplete:false,
                        list_item_heght:40,
                        list_width:380,
                        file:timeinfo
                    }
                }
                if(videoSW){
                    window.jwConfig.plugins.cueswhelper = {
                        dockname:'教学环节',
                        title:"课程名称:"+video.title,
                        introduction:video.remark,
                        repeatable:false,
                        oncomplete:false,
                        list_item_heght:40,
                        list_width:380,
                        file:videoSW
                    }
                }

                jwplayer("OnlinePlayer" + PlayerHash).setup(jwConfig);
    
                if (options.seekTime){
                    // if http
                    // jwplayer("OnlinePlayer" + PlayerHash).onReady(function() {
                    //     setTimeout(function() { jwplayer("OnlinePlayer" + PlayerHash).seek(options.seekTime) }, 500)
                    // })
                    // if rtmp
                    jwplayer("OnlinePlayer" + PlayerHash).on("firstFrame",function(){
                        jwplayer("OnlinePlayer" + PlayerHash).seek(options.seekTime)
                    })
                }
                jwplayer("OnlinePlayer" + PlayerHash).onError(function(e){
                    // TODO...
                    // vm.errObj = e;
                    var errMes='';
                    if(e.message=="Error loading stream: Manifest not found or invalid"){
                        errMes = "加载视频流出错"
                    }
                    if(e.message=="Error loading stream: ID not found on server"){
                        errMes = "视频流不存在"
                    }
                    if(e.message=="Error loading stream: Could not connect to server"){
                        errMes = "服务器连接失败"
                    }
                    if(errMes==''){
                        errMes = e.message
                    }
                    $('#OnlinePlayerContainer').append('<div class="errCover"><div class="centerbox"><h3>播放失败</h3><h4>错误提示:'+errMes+'</h4></div></div>');

                    console.log(e)
                })
                window.jw = jwplayer("OnlinePlayer" + PlayerHash);
                window.player = null;
                return {
                    errorCode: 0,
                    message: "等待直播中..."
                }
                return {
                        errorCode: 0,
                        message: "等待直播中..."
                    }
            }else {
                return {
                    errorCode: 5,
                    message: "未知视频流格式"
                }
            }
        }
    }

})
